#include "logger.h"

#include <cstdarg>
#include <cstring>
#include <cstdlib>
#include <ctime>

Logger::Logger(const char *dir, const char *fname)
{
    size_t dir_len = strlen(dir);
    size_t fname_len = strlen(fname);

    flog_path = new char[dir_len + fname_len + 2];
    ffatal_path = new char[dir_len + fname_len + 5];

    if (flog_path == NULL || ffatal_path == NULL) {
        fprintf(stderr, "Logger allocate memory failed!\n");
        exit(1);
    }

    sprintf(flog_path, "%s/%s", dir, fname);
    sprintf(ffatal_path, "%s/%s.wf", dir, fname);

    open_log_file();
}

Logger::Logger(const char *fname)
{
    flog_path = new char[strlen(fname) + 1];
    ffatal_path = new char[strlen(fname) + 4];

    if (flog_path == NULL || ffatal_path == NULL) {
        fprintf(stderr, "Logger allocate memory failed!\n");
        exit(1);
    }

    sprintf(flog_path, "%s", fname);
    sprintf(ffatal_path, "%s.wf", fname);

    open_log_file();
}

Logger::~Logger()
{
    delete [] flog_path;
    delete [] ffatal_path;

    fclose(flog);
    fclose(ffatal);
}

void
Logger::write_fatal(const char *fmt, ...)
{
    va_list ap;
    char buffer[4096], time_str[100];
    time_t t;  
    struct tm *tp;

    time(&t);
    tp = localtime(&t);
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tp);

    va_start(ap, fmt);
    vsprintf(buffer, fmt, ap);
    fprintf(ffatal, "[%s][FATAL]%s\n", time_str, buffer);
    va_end(ap);
}

void
Logger::write_warning(const char *fmt, ...)
{
    va_list ap;
    char buffer[4096], time_str[100];
    time_t t;
    struct tm *tp;

    time(&t);
    tp = localtime(&t);
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tp);

    va_start(ap, fmt);
    vsprintf(buffer, fmt, ap);
    fprintf(ffatal, "[%s][WARNING]%s\n", time_str, buffer);
    va_end(ap);
}

void
Logger::write_notice(const char *fmt, ...)
{
    va_list ap;
    char buffer[4096], time_str[100];
    time_t t;
    struct tm *tp;

    time(&t);
    tp = localtime(&t);
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tp);

    va_start(ap, fmt);
    vsprintf(buffer, fmt, ap);
    fprintf(flog, "[%s][NOTICE]%s\n", time_str, buffer);
    va_end(ap);
}

void
Logger::open_log_file()
{
    flog = fopen(flog_path, "a");
    if (flog == NULL) {
        fprintf(stderr, "Opening file [%s] failed!\n", flog_path);
        exit(1);
    }

    ffatal = fopen(ffatal_path, "a");
    if (ffatal == NULL) {
        fprintf(stderr, "Opening file [%s] failed!\n", ffatal_path);
        exit(1);
    }
}
